package com.emiage.ddutils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Created by LiJZ on 2016/7/22.
 */
public class AppInfoUtils {
	public static final File SDCARD = Environment.getExternalStorageDirectory();
	private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
	private static ProgressDialog mProgress = null;
	private static DisplayMetrics displayMetrics = new DisplayMetrics();
	private static int id;

	public static String toHexString(byte[] b) {
		// String to byte
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
			sb.append(HEX_DIGITS[b[i] & 0x0f]);
		}
		return sb.toString();
	}

	/**
	 * 生成Md5
	 *
	 * @param s 字符串
	 * @return 字符串的MD5值
	 */
	public static String md5(String s) {
		try {
			// Create MD5 Hash
			MessageDigest digest = MessageDigest
					.getInstance("MD5");
			digest.update(s.getBytes());
			byte messageDigest[] = digest.digest();

			return toHexString(messageDigest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return "";
	}

	/**
	 * Json字符串转化成JSONObject
	 *
	 * @param str
	 * @return JSONObject对象
	 * @throws Exception
	 */
	public static JSONObject stringToJSONObject(String str) throws Exception {
		try {
			return new JSONObject(str);
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 方法描述：安装一个Apk
	 *
	 * @return 是否成功
	 */
	public static boolean isAppInstall(Context context, String packname) {
		PackageManager manager = context.getPackageManager();
		@SuppressWarnings("rawtypes")
		List pkgList = manager.getInstalledPackages(0);
		for (int i = 0; i < pkgList.size(); i++) {
			PackageInfo pI = (PackageInfo) pkgList.get(i);
			if (pI.packageName.equalsIgnoreCase(packname)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取一个apk的包信息
	 *
	 * @param context         上下文
	 * @param archiveFilePath apk本地路径
	 * @return apk的包信息
	 */
	public static PackageInfo getApkInfo(Context context, String archiveFilePath) {
		PackageManager pm = context.getPackageManager();
		PackageInfo apkInfo = pm.getPackageArchiveInfo(archiveFilePath, 128);
		return apkInfo;
	}

	/**
	 * 方法描述：获取imsi码
	 *
	 * @return imsi码
	 */
	public static String getIMSI(Context context) {
		TelephonyManager phone = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String imsi = phone.getSubscriberId();
		return imsi == null ? "" : imsi;
	}

	/**
	 * imei和mac地址的md5值
	 *
	 * @param context
	 * @return imei和mac地址的md5值
	 */
	public static String getIMEIAndMacAddressMD5(Context context) {
		String xid = "";
		xid = md5(getIMEI(context) + getMacAddress(context));
		return xid;

	}

	/**
	 * 方法描述：获取IMEI
	 */
	public static String getIMEI(Context context) {
		SharedPreferences sp = context.getSharedPreferences("config",
				Context.MODE_PRIVATE);
		String imei = sp.getString("imei", "");
		if (imei == "") {
			TelephonyManager tm = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			imei = tm.getDeviceId();
			if (imei != null && imei != "") {
				SharedPreferences.Editor edit = sp.edit();
				edit.putString("imei", imei);
				edit.commit();
			} else {
				return "";
			}
		}

		return imei;
	}

	/**
	 * 方法描述：获取手机型号
	 */
	public static String getPhoneModle(Context context) {
		return android.os.Build.MODEL;
	}

	/**
	 * 获取版本号
	 *
	 * @param context
	 * @return 获取版本号
	 */
	public static int getVersionCode(Context context) {

		PackageInfo packageInfo = null;
		try {
			packageInfo = context.getApplicationContext().getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return 0;


	}

	/**
	 * 获取版本名
	 *
	 * @param context
	 * @return 获取版本名
	 */
	public static String getVersionName(Context context) {
		PackageInfo packageInfo = null;
		try {
			packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionName;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 获取Sim卡状态
	 *
	 * @param context 上下文
	 * @return 获取Sim卡状态码
	 */
	public static int getSimState(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getSimState();
	}

	/**
	 * 获取电话号码
	 *
	 * @param context 上下文
	 * @return 获取电话号码
	 * @throws Exception
	 */
	public static String getPhoneNumber(Context context) throws Exception {
		String phoneNumber = "";
		try {
			TelephonyManager tm = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			phoneNumber = tm.getLine1Number();
		} catch (Exception e) {
			throw new RuntimeException(
					"android.permission.READ_PHONE_STATE should be add to AndroidManifest.xml!");
		}
		return phoneNumber == null ? "" : phoneNumber;
	}

	/**
	 * 方法描述：获取MAC地址
	 *
	 * @param context 上下文
	 * @return 获取MAC地址
	 */
	public static String getMacAddress(Context context) {
		SharedPreferences sp = context.getSharedPreferences("config",
				Context.MODE_PRIVATE);
		String macAddr = sp.getString("mac", "");
		if (macAddr == "") {
			WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			try {
				WifiInfo wifiInfo = wifi.getConnectionInfo();
				macAddr = wifiInfo.getMacAddress();
				if (macAddr != null && macAddr != "") {
					SharedPreferences.Editor edit = sp.edit();
					edit.putString("mac", macAddr);
					edit.commit();
				} else {
					return "";
				}

			} catch (Exception e) {
				e.printStackTrace();
				LogUtils.d("android.permission.ACCESS_WIFI_STATE should be add to AndroidManifest.xml!");
			}
		}

		return macAddr;
	}
}
